package com.chb.docter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chb.docter.mapper.PatientFileMapper;
import com.chb.docter.mapper.PatientMapper;
import com.chb.docter.service.PatientFileService;
import com.hos.entity.his.Patient;
import com.hos.entity.his.PatientFile;
import com.hos.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author: 陈海彬
 * @date: Created in 2023/12/26 11:05
 * @description:
 * @modified By:
 * @version:
 */
@Service
public class PatientFileServiceImpl implements PatientFileService {

    @Resource
    private PatientFileMapper patientFileMapper;
    @Resource
    private PatientMapper patientMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PatientFile addFile(PatientFile patientFile) {
        patientFile.setCreateTime(new Date());
        patientFile.setUpdateTime(new Date());
        // 设置患者id
        patientFile.setPatientId(getPatientToken().getPatientId());
        this.patientFileMapper.insert(patientFile);
        return patientFile;
    }

    @Override
    public List<PatientFile> getAllPatientFile() {
        LambdaQueryWrapper<PatientFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PatientFile::getPatientId, getPatientToken().getPatientId());
        return this.patientFileMapper.selectList(wrapper);
    }

    @Override
    public PatientFile getPatientFileById(String id) {
        return this.patientFileMapper.selectById(id);
    }

    @Override
    public String putPatientFileById(String id, PatientFile patientFile) {
        patientFile.setPatientId(id);
        this.patientFileMapper.updateById(patientFile);
        return "修改成功";
    }

    @Override
    public String deleteMemberAddressById(String id) {
        int i = this.patientFileMapper.deleteById(id);
        return i > 0 ? "删除成功" : "删除失败";
    }

    /**
     * @return com.hos.entity.sys.User
     * @create by: 陈海彬
     * @description: 获取请求用户的信息
     * @create time: 2023/12/12 10:39
     */
    private Patient getPatientToken() {
        String token = WebUtil.getToken();
        String phone = redisTemplate.opsForValue().get("user:" + token);
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Patient::getPhone, phone);
        Patient patient = this.patientMapper.selectOne(wrapper);
        patient.setPassword("");
        return patient;
    }
}